package com.xuzimian.globaldemo.spring.springmvc.config;

import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 提供指定目录下的所有静态文件（html）地址
 *
 * @program: global-demo
 * @description: 静态文件统配类
 * @author: xzm
 * @create: 2019-04-25 14:45
 **/
@Service
public class StaticPagePathFinder {
    private ResourcePatternResolver resourcePatternResolver;

    @Autowired
    public StaticPagePathFinder(ResourcePatternResolver resourcePatternResolver) {
        this.resourcePatternResolver = resourcePatternResolver;
    }

    public static class PagePaths {
        private String filePath;
        private String urlPath;

        public PagePaths(String urlPath, String filePath) {
            this.filePath = filePath;  //实际的资源路径
            this.urlPath = urlPath;   //请求的资源路径
        }

        public String getFilePath() {
            return this.filePath;
        }

        public String getUrlPath() {
            return this.urlPath;
        }

        @Override
        public String toString() {
            return this.getUrlPath() + ";" + this.getFilePath();
        }
    }

    public List<PagePaths> findPath() throws IOException {
        Optional<Resource> baseResource = Optional.ofNullable(resourcePatternResolver.getResource("classpath:/templates/pages"));

        if (baseResource.isPresent() && baseResource.get().exists()) {
            String baseUrl = baseResource.get().getURL().getPath();
            Resource[] resources = resourcePatternResolver.getResources("classpath:/templates/pages/**/*.html");
            List<PagePaths> list = new ArrayList<>();
            for (Resource resource : resources) {
                System.out.println(new PagePaths(buildRequestMapping(resource.getURL().getPath()), relativeFliePath(baseUrl, resource)) + "hahaha");
                list.add(new PagePaths(buildRequestMapping(resource.getURL().getPath()), relativeFliePath(baseUrl, resource)));
            }
            return list;
        } else {
            return Lists.newArrayList();
        }
    }

    private String relativeFliePath(String basePath, Resource resource) throws IOException {
        return resource.getURL().getPath().substring(basePath.length()).replace(".html", "");
    }

    private String buildRequestMapping(String filePath) {
        return filePath.substring(filePath.lastIndexOf("/")).replace(".html", "");
    }

}
